package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.result.PageResult;
import com.sky.service.CategoryService;
import com.sky.service.DishService;
import com.sky.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

import static org.apache.commons.lang3.ObjectUtils.min;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Override
    public PageResult pageQuery(CategoryPageQueryDTO categoryPageQueryDTO) {

        int pageNum = categoryPageQueryDTO.getPage();
        int pageSize = categoryPageQueryDTO.getPageSize();

        String name = categoryPageQueryDTO.getName();
        Integer type = categoryPageQueryDTO.getType();

        // 构造分页条件
        Page<Category> page = Page.of(pageNum, pageSize);

        // 构造查询条件
        lambdaQuery()
                .like(name != null, Category::getName, name)
                .eq(type != null, Category::getType, type)
                .page(page);

        PageResult pageResult = new PageResult();


        // 设置属性
        // TODO 分页查询失败，需要修改
        pageResult.setTotal(page.getRecords().size());


        // 手动分页

        // 左端 = （页数 - 1）* 每页条数
        int l = (pageNum - 1) * pageSize;

        // 左端起点超出起点
        if (l >= page.getRecords().size()) {
            return pageResult;
        }

        // 右端 = 左端 +
        int r = l + pageSize;
        r = min(r, page.getRecords().size());
        pageResult.setRecords(page.getRecords().subList(l, r));

        return pageResult;


    }

    @Override
//    @AutoFill(value = OperationType.INSERT)
    public void create(CategoryDTO categoryDTO) {
        Category category = new Category();

        //属性拷贝
        BeanUtils.copyProperties(categoryDTO, category);

        //分类状态默认为禁用状态0
        category.setStatus(StatusConstant.DISABLE);

        //设置创建时间、修改时间、创建人、修改人
        category.setCreateTime(LocalDateTime.now());
        category.setCreateUser(BaseContext.getCurrentId());

        category.setUpdateTime(LocalDateTime.now());
        category.setUpdateUser(BaseContext.getCurrentId());

        categoryMapper.insert(category);

    }

    @Override
    public void deleteById(Long id) {

        //查询当前分类是否关联了菜品，如果关联了就抛出业务异常
        Long count = dishService.countByCategoryId(id);
        if (count > 0) {
            //当前分类下有菜品，不能删除
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }

//        查询当前分类是否关联了套餐，如果关联了就抛出业务异常
        count = setmealService.countByCategoryId(id);
        if (count > 0) {
            //当前分类下有菜品，不能删除
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }

        categoryMapper.deleteById(id);
    }

    @Override
//    @AutoFill(value = OperationType.UPDATE)
    public Category updateById(CategoryDTO categoryDTO) {
        Long id = categoryDTO.getId();

        // 查询待修改的员工
        Category category = categoryMapper.selectById(id);

        // 拷贝属性
        BeanUtils.copyProperties(categoryDTO, category);
        // 设置修改任何修改时间
        //设置修改时间、修改人
        category.setUpdateTime(LocalDateTime.now());
        category.setUpdateUser(BaseContext.getCurrentId());

        // 构造修改条件
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<Category>()
                .eq(Category::getId, id);
        // 修改员工信息
        categoryMapper.update(category, categoryLambdaQueryWrapper);

        return category;
    }

    @Override
//    @AutoFill(value = OperationType.UPDATE)
    public Category startOrStop(Integer status, Long id) {
        Category category = categoryMapper.selectById(id);

        if (category == null) {
            return null;
        }

        category.setStatus(status);

        //设置修改时间、修改人
        category.setUpdateTime(LocalDateTime.now());
        category.setUpdateUser(BaseContext.getCurrentId());


        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<Category>()
                .eq(Category::getId, id);
        categoryMapper.update(category, lambdaQueryWrapper);

        return category;

    }

    @Override
    public List<Category> listByType(Integer type) {

        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<Category>()
                .eq(type != null, Category::getType, type);

        return categoryMapper.selectList(lambdaQueryWrapper);
    }
}
